package com.acheli.registry.config;

import com.acheli.ACHeli;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import net.minecraftforge.registries.ForgeRegistries;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

// An example config class. This is not required, but it's a good idea to have one to keep your config organized.
// Demonstrates how to use Forge's config APIs
@Mod.EventBusSubscriber(modid = ACHeli.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class Config
{
    // 获取 Minecraft 实例目录
    private static final Path MINECRAFT_DIR = Minecraft.getInstance().gameDirectory.toPath();
    // 自定义配置文件路径
    public static final Path CUSTOM_CONFIG_PATH = MINECRAFT_DIR
            .resolve("config")
            .resolve(ACHeli.MODID);
    public static final Path VPackFolder = CUSTOM_CONFIG_PATH.resolve("vehicles");


    public static List<Path> listDirectory(Path path){
        List<Path> li = new ArrayList<>();
        try {
            // 递归遍历所有文件，筛选出 .json 文件并打印路径
            li = Files.list(path)
                    .filter(Files::isDirectory) // 仅处理普通文件（非目录）
                    .toList(); // 打印完整路径
        } catch (IOException e) {
        }
        return li;
    }

    public static List<Path> walkDirectory(Path path){
        List<Path> li = new ArrayList<>();
        try {
            // 递归遍历所有文件，筛选出 .json 文件并打印路径
            li = Files.walk(path)
                    .filter(Files::isDirectory) // 仅处理普通文件（非目录）
                    .toList(); // 打印完整路径
        } catch (IOException e) {
        }
        return li;
    }
    public static List<Path> listPath(Path path){
        List<Path> li = new ArrayList<>();
        try {
            // 递归遍历所有文件，筛选出 .json 文件并打印路径
            li = Files.list(path)
                    .filter(Files::isRegularFile) // 仅处理普通文件（非目录）
                    .toList(); // 打印完整路径
        } catch (IOException e) {
        }
        return li;
    }
    public static List<Path> walkPath(Path path){
        List<Path> li = new ArrayList<>();
        try {
            // 递归遍历所有文件，筛选出 .json 文件并打印路径
            li = Files.walk(path)
                    .filter(Files::isRegularFile) // 仅处理普通文件（非目录）
                    .toList(); // 打印完整路径
        } catch (IOException e) {
        }
        return li;
    }
    public static void makeSureExistsVPackFolder(){
        if (!Files.exists(VPackFolder)) {
            try {
                Files.createDirectory(VPackFolder);
            } catch (IOException e) {
                ACHeli.LOGGER.warn("Failed to create VPackFolder.");
            }
        }
    }

    /**
     * 将文件内容读取到字节数组输入流（自动关闭资源）
     * @param file 要读取的文件对象
     * @return ByteArrayInputStream 或 null（读取失败时）
     */
    public static ByteArrayInputStream fileToByteArrayStream(File file) {
        try {
            byte[] bytes = Files.readAllBytes(file.toPath());
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            System.err.println("File failed to load" + e.getMessage());
            return null;
        }
    }

    /**
     * 安全版（带异常抛出）
     * @param file 要读取的文件
     * @return 包含文件内容的字节数组输入流
     * @throws IOException 当文件读取失败时抛出
     */
    public static ByteArrayInputStream fileToByteArrayStreamSafe(File file) throws IOException {
        byte[] bytes = Files.readAllBytes(file.toPath());
        return new ByteArrayInputStream(bytes);
    }

    // 加载或创建配置文件
    public static Object loadConfig(Path FilePath, Object configData) {
        Gson gson = new Gson();
        try {
            if (!Files.exists(FilePath)) {
                createDefaultConfig(FilePath, configData); // 如果文件不存在，创建默认配置
            }
            String json = Files.readString(FilePath);
            configData = gson.fromJson(json, configData.getClass());
        } catch (IOException e) {
            e.printStackTrace();
            // 加载失败时使用默认值
        }
        return configData;
    }

    // 生成默认配置文件
    private static void createDefaultConfig(Path filePath, Object configData) throws IOException {
        // 创建目录（如果不存在）
        Files.createDirectories(filePath.getParent());
        // 写入文件
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(configData);
        Files.writeString(filePath, json);
    }

    private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();

    private static final ForgeConfigSpec.BooleanValue JS_DEBUG_MODE = BUILDER
            .comment("A bool value. If it is true, javascript will show the debug alerts.")
            .define("jsMode", false);

//    private static final ForgeConfigSpec.IntValue MAGIC_NUMBER = BUILDER
//            .comment("A magic number")
//            .defineInRange("magicNumber", 42, 0, Integer.MAX_VALUE);
//
//    public static final ForgeConfigSpec.ConfigValue<String> MAGIC_NUMBER_INTRODUCTION = BUILDER
//            .comment("What you want the introduction message to be for the magic number")
//            .define("magicNumberIntroduction", "The magic number is... ");
//
//    // a list of strings that are treated as resource locations for items
//    private static final ForgeConfigSpec.ConfigValue<List<? extends String>> ITEM_STRINGS = BUILDER
//            .comment("A list of items to log on common setup.")
//            .defineListAllowEmpty("items", List.of("minecraft:iron_ingot"), Config::validateItemName);

    public static final ForgeConfigSpec SPEC = BUILDER.build();

    public static boolean jsDebugMode;
//    public static int magicNumber;
//    public static String magicNumberIntroduction;
//    public static Set<Item> items;

//    private static boolean validateItemName(final Object obj)
//    {
//        return obj instanceof final String itemName && ForgeRegistries.ITEMS.containsKey(ResourceLocation.parse(itemName));
//    }

    @SubscribeEvent
    static void onLoad(final ModConfigEvent event)
    {
        jsDebugMode = JS_DEBUG_MODE.get();
//        magicNumber = MAGIC_NUMBER.get();
//        magicNumberIntroduction = MAGIC_NUMBER_INTRODUCTION.get();

        // convert the list of strings into a set of items
//        items = ITEM_STRINGS.get().stream()
//                .map(itemName -> ForgeRegistries.ITEMS.getValue(ResourceLocation.parse(itemName)))
//                .collect(Collectors.toSet());
    }
}
